import { getCartList, updateCart, deleteCart } from '@/api/cart'
import { Toast } from 'vant'

export default {
  namespaced: true,
  state () {
    return {
      list: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.list = newList
    },
    // 主动全选全不选
    toggleAllCheck (state, flag) {
      state.list.forEach(item => {
        item.checked = flag
      })
    },
    // 小选框
    toggleCheck (state, goodsId) {
      const goods = state.list.find(item => item.goods_id === goodsId)
      goods.checked = !goods.checked
    },
    updateCartMu (state, { goodsId, goodsNum }) {
      state.list.find(item => item.goods_id === goodsId).goods_num = goodsNum
    }
  },
  actions: {
    async getCartAction (context) {
      const { data: { list } } = await getCartList()
      // 手动给每一项数据添加一个checked属性
      list.forEach(item => {
        item.checked = false
      })
      context.commit('setCartList', list)
    },
    async updateCartAction (context, { goodsId, goodsNum, goodsSkuId }) {
      // 先本地修改，再请求服务器
      context.commit('updateCartMu', { goodsId, goodsNum })
      await updateCart(goodsId, goodsNum, goodsSkuId)
      context.dispatch('getCartAction')
    },
    async delCartAction (context) {
      // cartIds是一个数组，是被选中的商品的id
      const cartIds = context.getters.selectList.map(item => item.id)
      await deleteCart(cartIds)
      Toast.success('删除成功')
      // 删除之后，重新获取购物车列表
      context.dispatch('getCartAction')
    }
  },
  getters: {
    // 商品总数也是变化的，不能用服务器的goods_num
    cartTotal (state) {
      return state.list.reduce((total, item) => total + item.goods_num
        , 0)
    },
    // 基于勾选商品计算数量、总价
    selectList (state) {
      return state.list.filter(item => item.checked)
    },
    selectCount (state, getters) {
      return getters.selectList
        .reduce((total, item) => total + item.goods_num, 0)
    },
    selectPrice (state, getters) {
      return getters.selectList
        .reduce((sum, item) => {
          return sum + item.goods_num * item.goods.goods_price_min
        }, 0)
        .toFixed(2)
    },
    // 被动全选
    isAllChecked (state) {
      return state.list.every(item => item.checked)
    }
  }
}
